<style lang="scss" scoped>
::v-deep {
  .brand-condition {
    width: 120px;
    .el-input {
      width: 100% !important;

      input {
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
      }
    }
  }

  .brand-search {
    width: 260px;
    .el-input {
      width: 100% !important;
      input {
        width: 100% !important;
        border-left: none;
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
      }
    }
  }

}
</style>

<template>
  <div>
    <el-select v-model="brand.condition" placeholder="请选择搜索条件" class="brand-condition">
      <el-option label="中文名称" value="brand_name" />
      <el-option label="英文名称" value="brand_en_name" />
      <el-option label="发源地名称" value="source_name" />
      <el-option label="品牌简拼" value="py_short" />
      <el-option label="品牌全拼" value="py" />
    </el-select>

    <el-select
      v-model="brand.value"
      clearable
      filterable
      remote
      reserve-keyword
      placeholder="请输入搜索关键词"
      :remote-method="remoteMethod"
      :loading="brand.loading"
      class="brand-search"
      :style="{ width: inputWidth }"
      @change="selectBrand"
    >
      <i slot="prefix" class="el-input__icon el-icon-search" style="font-size: 16px" />
      <el-option
        v-for="item in brand.options"
        :key="item.brand_id"
        :label="item.brand_name"
        :value="item.brand_id"
      />
    </el-select>
  </div>
</template>

<script>

import _ from 'lodash'

import { handleList } from '@/api/base/brand'

export default {

  props: {
    inputWidth: {
      type: String,
      default: '260px'
    }
  },

  data() {
    return {
      brand: {
        value: '',
        condition: 'brand_name',
        loading: false,
        options: []
      }
    }
  },

  created() {

  },

  methods: {
    remoteMethod(query) {
      if (query === '') return
      this.brand.options = []
      this.brand.loading = true
      this.searchBrand(query)
    },

    searchBrand(query, page = 1) {
      handleList({
        page: page,
        limit: 100,
        brandWhere: this.brand.condition,
        word: query
      }).then(res => {
        _.forEach(res.data.data, item => {
          this.brand.options.push(item)
        })

        if (page < res.data.last_page) {
          this.searchBrand(query, ++page)
        } else {
          this.brand.loading = false
        }
      })
    },

    selectBrand() {
      const brandInfo = _.find(this.brand.options, {
        brand_id: this.brand.value
      })

      this.$emit('select', brandInfo)
    }
  }
}
</script>
